package com.msoe.utils;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.security.Security;


public final class Emailer   {
	
	private static final String GMAILEmailHost = "smtp.gmail.com";
	private static final String FromAddress = "MOZERide@gmail.com";
	private static final String SMTP_PORT = "465";
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	
	public boolean sendNewUserMessage(String email, String username, String password){
		String subject = "Welcome to MSOE Ride!";
		String body = "Congratulations!\n\nYou have successfully signed up for the MSOE Ride application."+
		"\nPlease use the password below to login to the application for the first time.";
		body += "\n\n\tUsername:"+username+"\n\tPassword:"+password+"\n\nThank you for choosing to Ride MSOE style!";
		
		boolean fail = false;
		
		try{
			sendMessage(email, subject, body);
		} catch (AddressException ae) {
			System.out.println("Bad address");
			fail = true;
		} catch (SendFailedException sf) {
			System.out.println("Failed to send message 1");
			fail = true;
		} catch (MessagingException mexc) {
			System.out.println("Failed to send message 2");
			fail = true;
		}
		
		return !fail;
	}

	private void sendMessage(String ToAddress, String Subject, String Body) throws AddressException, SendFailedException, MessagingException {
		
		boolean debug = false;
		
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		
		Properties p = System.getProperties();
		p.put("mail.smtp.host", GMAILEmailHost);
		p.put("mail.smtp.auth", "true");
		p.put("mail.debug", String.valueOf(debug));
		p.put("mail.smtp.port", SMTP_PORT);
		p.put("mail.smtp.socketFactory.port", SMTP_PORT);
		p.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		p.put("mail.smtp.socketFactory.fallback", "false");

		Session session = Session.getDefaultInstance(p, new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(FromAddress, "IneedAride!");
				}
			} );
		session.setDebug(debug);
		
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(FromAddress));
		message.setRecipients(Message.RecipientType.TO, InternetAddress
				.parse(ToAddress));
		message.setSubject(Subject);
		message.setText(Body);
		
		Transport.send(message);
	}
}
